#coding=utf-8
from __future__ import with_statement
from uliweb import expose
import generic.views as g_views
from uliweb.core.html import Tag

from uliweb import expose
from sqlalchemy import *
from uliweb.orm import *
from sqlalchemy.sql import select

from uliweb import orm
import os

layout = 'tasks_layout.html'

def __begin__():
    from uliweb import function
    return function('require_login')()
    
def task_id(get_url):
    def _f(value, obj, get_url=get_url):
        return str(Tag('a', value, href=get_url('view', obj.id)))
    return _f

def boolean_convert(b, obj):
    if b:
        return '<div class="ui-icon ui-icon-check"></div>'
    else:
        return '<div class="ui-icon ui-icon-closethick"></div>'

def get_model_name(task_type):
    if task_type == 'develop':
        return 'tasks_develop'
    elif task_type == 'researches':
        return 'researches'
    else:
        return 'tasks'
    
def get_task_type_name(task_type):
    if task_type == 'develop':
        return '开发'
    elif task_type == 'researches':
        return '可研'
    else:
        return '非开发'
    
def get_model_from_task_type(task_type):
    from uliweb import settings
    from uliweb.orm import get_model
    
    if task_type in dict(settings.get_var('PARA/TASK_TYPE_DEVELOP', [])):
        Task = get_model('tasks_develop')
        _type = 'develop'
    elif task_type in dict(settings.get_var('PARA/TASK_TYPE_NONDEVELOP', [])):
        Task = get_model('tasks')
        _type = 'nondevelop'
    else:
        Task = get_model('researches')
        _type = 'researches'
    return _type, Task
    
#@expose('/tasks', defaults={'task_type':'develop'})
@expose('/tasks/<task_type>/list')
def task_develop_list(task_type):
    from uliweb.utils.generic import ListView
    from uliweb.orm import get_model
    from query import create_task_query
    from sqlalchemy.sql import or_,and_
    from tests.views import tests_test_list
    
    #处理条件
    query_view = create_task_query(task_type, url_for(task_develop_list, task_type=task_type))
    c = query_view.run()
    
    get_url = g_views.get_url('/tasks/%s' % task_type, restful=True)
    model = get_model_name(task_type)
    Requirement = get_model('requirement')
    Req_test = get_model('test_finish_rate')
    Plan = get_model('plan')
    Planexecute = get_model('planexecute')
    Task = get_model(model)
    
    pageno = int(request.values.get('page', 1)) - 1
    rows_per_page=int(request.values.get('rows', settings.get_var('PARA/ROWS_PER_PAGE', 10)))
    
    condition = None
    requirements_ids = [x[0] for x in Requirement.get_user_requirements(request.user).values('id')]
    if task_type == 'develop' or task_type == 'researches':
        #获得准开发需求。开发主管如果“只显示我的任务”选择“是”，则查看自已中心的任务；
        if c.get('only_mine') == '1':
            if request.user.department == '2' and request.user.is_gm:
                condition = (Task.c.kfzx == request.user._kfzx_) & condition
            else:
                condition = Task.c.task_sys.in_(request.user.users_systems.ids())& condition
        #开发主管如果“只显示我的任务”选择“全部”，则查看所有任务
        elif c.get('only_mine') == '0' and request.user.department == '2' and (request.user.is_gm or not request.user.is_manager):
            pass
        else:
            condition = Task.c.requirement.in_(requirements_ids)& condition
    #开发部门，非主管看自已系统对应的任务
    if request.user.department == '2':
        if not request.user.is_gm and request.user.is_manager:
            condition = or_(Task.c.requirement.in_(requirements_ids), Task.c.task_sys.in_(request.user.users_systems.ids())) & condition
        if task_type == 'nondevelop':
            condition = (~Task.c.task_type.in_(settings.get_var('PARA/TASK_TEST_TYPE'))) & condition
    elif request.user.department == '3':
        #测试主管可以查看全部任务
        #测试非主管可以查看自已所属系统的任务及修改人为自已的任务
        if not request.user.is_gm:
            condition = or_(Task.c.modified_user == request.user.id, Task.c.task_sys.in_(request.user.users_systems.ids())) & condition
        if task_type == 'nondevelop':
            condition = (Task.c.task_type.in_(settings.get_var('PARA/TASK_TEST_TYPE'))) & condition
      
    #增加显示未完成信息处理
    if c.get('closed') != '1':
        if task_type == 'develop':
            condition = (Task.c.stage != 'FN') & condition
        elif task_type == 'researches':
            condition = (Task.c.status != '3') & condition
            
    if c.get('task_id'):
        condition = (Task.c.task_id.like('%'+c['task_id']+'%')) & condition
    if c.get('requirement'):
        condition = (Task.c.requirement == int(c['requirement'])) & condition
    if c.get('assignment'):
        condition = (Task.c.assignment == int(c['assignment'])) & condition
    if c.get('kfzx'):
        condition = (Task.c.kfzx == int(c['kfzx'])) & condition
    if c.get('task_sys'):
        condition = (Task.c.task_sys == int(c['task_sys'])) & condition
    if c.get('status'):
        condition = Task.c.status.in_(c['status']) & condition
    if c.get('name'):
        condition = (Task.c.name.like('%'+c['name']+'%') | Task.c.task_id.like('%'+c['name']+'%')) & condition
    if c.get('memo'):
        condition = (Task.c.memo.like('%'+c['memo']+'%')) & condition
    if c.get('task_type'):
        condition = Task.c.task_type.in_(c['task_type']) & condition
    if c.get('stage'):
        condition = Task.c.stage.in_(c['stage']) & condition
    if c.get('begin_date') and task_type == 'develop':
        condition = (Task.c.version_date >= c['begin_date']) & condition
    if c.get('end_date') and task_type == 'develop':
        condition = (Task.c.version_date <= c['end_date']) & condition
    if c.get('begin_created_date') and task_type == 'develop':
        condition = (Task.c.created_date >= c['begin_created_date']) & condition
    if c.get('end_created_date') and task_type == 'develop':
        condition = (Task.c.created_date <= c['end_created_date']) & condition
    
    if c.get('selfdev_if') and task_type == 'develop':
        condition = (Task.c.selfdev_if == c['selfdev_if']) & condition
    
    if request.GET.get('header_id') and task_type == 'develop':
        header_id = int(request.GET['header_id'])
        condition = or_((Task.c.id == header_id), (Task.c.version_headerId == header_id))
        
    def is_mine(value, obj):
        if request.user.users_systems.has(obj._task_sys_):
            return '<div class="ui-icon ui-icon-check"></div>'
        else:
            return '<div class="ui-icon ui-icon-closethick"></div>'
        
    def memo(value, obj):
        if value:
            return value[:settings.get_var("PARA/DOWNLOAD_MEMO_LENGTH")]
        else:
            return value
    #处理来自功能测试的信息
    def test_version(value, obj):
        sel = select([Req_test.c.id,Plan.c.end_date],
                       (and_(Req_test.c.system ==obj._task_sys_,
                             Plan.c.task == obj.id,
                             Plan.c.idn == '1030',
                             Req_test.c.version_date == Plan.c.end_date)))
        objs_rs =  sel.execute()             
        test_version = ''
        for row in objs_rs:
            num,version_date = row 
#            x=Req_test.get(and_(Req_test.c.system ==obj.task_sys,Req_test.c.version_date == obj.version_date))
#            num = x.id
            #print 'xxxxxxxxxxxxxx',num            
            if num:
               test_version = str(obj.task_sys.abbr)+'_'+str(version_date)
               return str(Tag('a', test_version, href=url_for(tests_test_list, system=obj._task_sys_,version_date=version_date)))
            
    def change_num(value, obj):
        sel = select([Req_test.c.change_num],
                    (and_(Req_test.c.system ==obj._task_sys_,
                          Plan.c.task == obj.id,
                          Plan.c.idn == '1030',
                        Req_test.c.version_date == Plan.c.end_date)))
        objs_rs =  sel.execute()
        change_num = None      
        for row in objs_rs:
            change_num, = row
        return change_num
       
    def test_finish_rate(value, obj):
        sel = select([Req_test.c.test_finish_rate],
                    (and_(Req_test.c.system ==obj._task_sys_,
                          Plan.c.task == obj.id,
                          Plan.c.idn == '1030',
                          Req_test.c.version_date == Plan.c.end_date)))
        objs_rs =  sel.execute() 
        test_finish_rate = None              
        for row in objs_rs:
            test_finish_rate, = row
            test_finish_rate = str(round(float(test_finish_rate),4)*100)+'%'
        return test_finish_rate
    
    def req_finish_end_date(value, obj):
        sel = select([Planexecute.c.finish_end_date],
                      (and_(Planexecute.c.task == obj.id,
                            Plan.c.id ==Planexecute.c.plan,
                            Plan.c.idn == '1010')))
        objs_rs =  sel.execute()
        req_finish_end_date = None
        for row in objs_rs:
            req_finish_end_date = row[0]
        return req_finish_end_date
    def design_finish_end_date(value, obj):
        sel = select([Planexecute.c.finish_end_date],
                        (and_(Planexecute.c.task == obj.id,
                            Plan.c.id ==Planexecute.c.plan,
                            Plan.c.idn == '1020')))
        objs_rs =  sel.execute()
        design_finish_end_date = None
        for row in objs_rs:
            design_finish_end_date = row[0]
        return design_finish_end_date
    
    def req_modified_date(value, obj):
        sel = select([Req_test.c.req_modified_date],
                    (and_(Req_test.c.system ==obj._task_sys_,
                        Req_test.c.version_date == obj.version_date)))
        objs_rs =  sel.execute() 
        req_modified_date = None              
        for row in objs_rs:
            req_modified_date, = row
        return req_modified_date
    
    def sub_sys(value, obj):
        return '<span title="%s">%s</span>' % (obj.sub_sys_name, value)
    #取计划时间
    def req_close_date(value, obj):
        req_close_date = None
        plan_obj = Plan.get(and_(Plan.c.task == obj.id, 
                            Plan.c.idn == '1010',
                            Plan.systems.in_(obj.task_sys)))
        if plan_obj:
            req_close_date = plan_obj.end_date
        else:
            if obj.version_headerId:
                version_headerId = obj._version_headerId_ 
                sel = select([Plan.c.end_date],
                              (and_(Plan.c.task == version_headerId,
                                    Plan.c.idn == '1010',
                                    Plan.systems.in_(obj.task_sys))))
                objs_rs =  sel.execute()
                for row in objs_rs:
                    req_close_date = row[0]
        return req_close_date
    def design_close_date(value, obj):
        design_close_date = None
        plan_obj = Plan.get(and_(Plan.c.task == obj.id, 
                            Plan.c.idn == '1020',
                            Plan.systems.in_(obj.task_sys)))
        if plan_obj:
            design_close_date = plan_obj.end_date
        else:
            if obj.version_headerId:
               version_headerId = obj._version_headerId_ 
               sel = select([Plan.c.end_date],
                              (and_(Plan.c.task == version_headerId,
                                    Plan.c.idn == '1020',
                                    Plan.systems.in_(obj.task_sys))))
               objs_rs =  sel.execute()
               for row in objs_rs:
                   design_close_date = row[0]
        return design_close_date
    
    def version_date(value, obj):
        version_date = None
        plan_obj = Plan.get(and_(Plan.c.task == obj.id, 
                            Plan.c.idn == '1030',
                            Plan.systems.in_(obj.task_sys)))
        if plan_obj:
            version_date = plan_obj.end_date
        else:
            if obj.version_headerId:
                version_headerId = obj._version_headerId_
                sel = select([Plan.c.end_date],
                              (and_(Plan.c.task == version_headerId,
                                    Plan.c.idn == '1030',
                                    Plan.systems.in_(obj.task_sys))))
                objs_rs =  sel.execute()
                for row in objs_rs:
                    version_date = row[0]
        return version_date
    def test_beginDate(value, obj):
        test_beginDate = None
        plan_obj = Plan.get(and_(Plan.c.task == obj.id, 
                            Plan.c.idn == '0060',
                            Plan.systems.in_(obj.task_sys)))
        if plan_obj:
            test_beginDate = plan_obj.begin_date
        else:
            if obj.version_headerId:
                version_headerId = obj._version_headerId_ 
            
                sel = select([Plan.c.begin_date],
                              (and_(Plan.c.task == version_headerId,
                                    Plan.c.idn == '0060',
                                    Plan.systems.in_(obj.task_sys))))
                objs_rs =  sel.execute()

                for row in objs_rs:
                    test_beginDate = row[0]
        return test_beginDate
    def test_finish_beginDate(value, obj):
        test_finish_beginDate = None
        sel = select([Planexecute.c.finish_begin_date],
                        (and_(Plan.c.idn == '0060',
                            Planexecute.c.task == obj.id,
                            Plan.c.id == Planexecute.c.plan)))
        objs_rs =  sel.execute()
        
        for row in objs_rs:
            test_finish_beginDate = row[0]
        return test_finish_beginDate
    def test_endDate(value, obj):
        test_endDate = None
        plan_obj = Plan.get(and_(Plan.c.task == obj.id, 
                            Plan.c.idn == '0060',
                            Plan.systems.in_(obj.task_sys)))
        if plan_obj:
            test_endDate = plan_obj.end_date
        else:
        
            if obj.version_headerId:
                version_headerId = obj._version_headerId_ 
            
                sel = select([Plan.c.end_date],
                              (and_(Plan.c.task == version_headerId,
                                    Plan.c.idn == '0060',
                                    Plan.systems.in_(obj.task_sys))))
                objs_rs =  sel.execute()
                for row in objs_rs:
                    test_endDate = row[0]
        return test_endDate
    
    def test_finish_endDate(value, obj):
        sel = select([Planexecute.c.finish_end_date],
                      (and_(Plan.c.idn == '0060',
                            Planexecute.c.task == obj.id,
                            Plan.c.id == Planexecute.c.plan)))
        objs_rs =  sel.execute()
        test_finish_endDate = None
        for row in objs_rs:
            test_finish_endDate = row[0]
        return test_finish_endDate
    
    def uat_begin_date(value, obj):
        uat_begin_date = None
        plan_obj = Plan.get(and_(Plan.c.task == obj.id, 
                            Plan.c.idn == '0070',
                            Plan.systems.in_(obj.task_sys)))
        if plan_obj:
            uat_begin_date = plan_obj.begin_date
        else:
            if obj.version_headerId:
                version_headerId = obj._version_headerId_ 
            
                sel = select([Plan.c.begin_date],
                              (and_(Plan.c.task == version_headerId,
                                    Plan.c.idn == '0070',
                                    Plan.systems.in_(obj.task_sys))))
                objs_rs =  sel.execute()
                for row in objs_rs:
                    uat_begin_date = row[0]
        return uat_begin_date
    
    def uat_finish_begin_date(value, obj):
        sel = select([Planexecute.c.finish_begin_date],
                      (and_(Plan.c.idn == '0070',
                            Planexecute.c.task == obj.id,
                            Plan.c.id == Planexecute.c.plan)))
        objs_rs =  sel.execute()
        uat_finish_begin_date = None
        for row in objs_rs:
            uat_finish_begin_date = row[0]
        return uat_finish_begin_date
    
    def uat_end_date(value, obj):
        uat_end_date = None
        plan_obj = Plan.get(and_(Plan.c.task == obj.id, 
                            Plan.c.idn == '0070',
                            Plan.systems.in_(obj.task_sys)))
        if plan_obj:
            uat_end_date = plan_obj.end_date
        else:
            if obj.version_headerId:
                version_headerId = obj._version_headerId_ 

                sel = select([Plan.c.end_date],
                              (and_(Plan.c.task == version_headerId,
                                    Plan.c.idn == '0070',
                                    Plan.systems.in_(obj.task_sys))))
                objs_rs =  sel.execute()
                for row in objs_rs:
                    uat_end_date = row[0]
        return uat_end_date
    
    def uat_finish_end_date(value, obj):
        
        sel = select([Planexecute.c.finish_end_date],
                      (and_(Plan.c.idn == '0070',
                            Planexecute.c.task == obj.id,
                            Plan.c.id == Planexecute.c.plan)))
        objs_rs =  sel.execute()
        uat_finish_end_date = None
        for row in objs_rs:
            uat_finish_end_date = row[0]
        return uat_finish_end_date
    
    def func_inst_begin_date(value, obj):
        func_inst_begin_date = None
        plan_obj = Plan.get(and_(Plan.c.task == obj.id, 
                            Plan.c.idn == '0090',
                            Plan.systems.in_(obj.task_sys)))
        if plan_obj:
            func_inst_begin_date = plan_obj.begin_date
        else:
            if obj.version_headerId:
                version_headerId = obj._version_headerId_ 
            
                sel = select([Plan.c.begin_date],
                              (and_(Plan.c.task == version_headerId,
                                    Plan.c.idn == '0090')))
                objs_rs =  sel.execute()
                for row in objs_rs:
                    func_inst_begin_date = row[0]
        return func_inst_begin_date
    
    def func_inst_finish_begin_date(value, obj):
        
        sel = select([Planexecute.c.finish_begin_date],
                      (and_(Plan.c.idn == '0090',
                            Planexecute.c.task == obj.id,
                            Plan.c.id == Planexecute.c.plan)))
        objs_rs =  sel.execute()
        func_inst_finish_begin_date = None
        for row in objs_rs:
            func_inst_finish_begin_date = row[0]
        return func_inst_finish_begin_date
    
    def func_inst_end_date(value, obj):
        func_inst_end_date = None
        plan_obj = Plan.get(and_(Plan.c.task == obj.id, 
                            Plan.c.idn == '0090',
                            Plan.systems.in_(obj.task_sys)))
        if plan_obj:
            func_inst_end_date = plan_obj.end_date
        else:
            if obj.version_headerId:
                version_headerId = obj._version_headerId_             
                sel = select([Plan.c.end_date],
                              (and_(Plan.c.task == version_headerId,
                                    Plan.c.idn == '0090',
                                    Plan.systems.in_(obj.task_sys))))
                objs_rs =  sel.execute()
                for row in objs_rs:
                    func_inst_end_date = row[0]
        return func_inst_end_date
    
    def func_inst_finish_end_date(value, obj):
        sel = select([Planexecute.c.finish_end_date],
                      (and_(Plan.c.idn == '0090',
                            Planexecute.c.task == obj.id,
                            Plan.c.id == Planexecute.c.plan)))
        objs_rs =  sel.execute()
        func_inst_finish_end_date = None
        for row in objs_rs:
            func_inst_finish_end_date = row[0]
        return func_inst_finish_end_date
    
    def tune_inst_begin_date(value, obj):
        tune_inst_begin_date = None
        plan_obj = Plan.get(and_(Plan.c.task == obj.id, 
                            Plan.c.idn == '0100',
                            Plan.systems.in_(obj.task_sys)))
        if plan_obj:
            tune_inst_begin_date = plan_obj.begin_date
        else:
            if obj.version_headerId:
                version_headerId = obj._version_headerId_ 
            
                sel = select([Plan.c.begin_date],
                              (and_(Plan.c.task == version_headerId,
                                    Plan.c.idn == '0100',
                                    Plan.systems.in_(obj.task_sys))))
                objs_rs =  sel.execute()
                for row in objs_rs:
                    tune_inst_begin_date = row[0]
        return tune_inst_begin_date
    
    def tune_inst_finish_begin_date(value, obj):
        sel = select([Planexecute.c.finish_begin_date],
                      (and_(Plan.c.idn == '0100',
                            Planexecute.c.task == obj.id,
                            Plan.c.id == Planexecute.c.plan)))
        objs_rs =  sel.execute()
        tune_inst_finish_begin_date = None
        for row in objs_rs:
            tune_inst_finish_begin_date = row[0]
        return tune_inst_finish_begin_date
    
    def tune_inst_end_date(value, obj):
        tune_inst_end_date = None
        plan_obj = Plan.get(and_(Plan.c.task == obj.id, 
                            Plan.c.idn == '0100',
                            Plan.systems.in_(obj.task_sys)))
        if plan_obj:
            tune_inst_end_date = plan_obj.end_date
        else:
            if obj.version_headerId:
                version_headerId = obj._version_headerId_ 

                sel = select([Plan.c.end_date],
                              (and_(Plan.c.task == version_headerId,
                                    Plan.c.idn == '0100',
                                    Plan.systems.in_(obj.task_sys))))
                objs_rs =  sel.execute()
                for row in objs_rs:
                    tune_inst_end_date = row[0]
        return tune_inst_end_date
    
    def tune_inst_finish_end_date(value, obj):

        sel = select([Planexecute.c.finish_end_date],
                      (and_(Plan.c.idn == '0100',
                            Planexecute.c.task == obj.id,
                            Plan.c.id == Planexecute.c.plan)))
        objs_rs =  sel.execute()
        tune_inst_finish_end_date = None
        for row in objs_rs:
            tune_inst_finish_end_date = row[0]
        return tune_inst_finish_end_date
    
    
              
    fields_convert_map = {'task_id':task_id(get_url), 'is_mine':is_mine, 
        'memo':memo,'test_version':test_version,'change_num':change_num,
        'test_finish_rate':test_finish_rate,'req_modified_date':req_modified_date,
        'req_finish_end_date':req_finish_end_date,'design_finish_end_date':design_finish_end_date,
        'sub_sys':sub_sys,'req_close_date':req_close_date,'design_close_date':design_close_date,
        'version_date':version_date,'test_beginDate':test_beginDate,
        'test_finish_beginDate':test_finish_beginDate,'test_endDate':test_endDate,
        'test_finish_endDate':test_finish_endDate,'uat_begin_date':uat_begin_date,
        'uat_finish_begin_date':uat_finish_begin_date,'uat_end_date':uat_end_date,
        'uat_finish_end_date':uat_finish_end_date,'func_inst_begin_date':func_inst_begin_date,
        'func_inst_finish_begin_date':func_inst_finish_begin_date,'func_inst_end_date':func_inst_end_date,
        'func_inst_finish_end_date':func_inst_finish_end_date,'tune_inst_begin_date':tune_inst_begin_date,
        'tune_inst_finish_begin_date':tune_inst_finish_begin_date,'tune_inst_end_date':tune_inst_end_date,
        'tune_inst_finish_end_date':tune_inst_finish_end_date}
    if task_type == 'develop':
        order_by = [Task.c.requirement, Task.c.version_date, Task.c.version_headerId, Task.c.task_id]
    else:
        order_by = [Task.c.requirement, Task.c.task_id]
    view =  ListView(Task, condition=condition, order_by=order_by,
        rows_per_page=rows_per_page, 
        pageno=pageno, id='tasks_table', fields_convert_map=fields_convert_map)
    view.types_convert_map = {orm.BooleanProperty:boolean_convert}
    
    if 'download' in request.GET:
        def download_is_mine(value, obj):
            if request.user.users_systems.has(obj._task_sys_):
                return u'是'
            else:
                return u'否'
            
        def download_risk_if(value, obj):
            if obj.risk_if:
                return u'是'
            else:
                return u'否'
            
        def download_test_version(value, obj):
            sel = select([Req_test.c.id],
                            (and_(Req_test.c.system ==obj._task_sys_,
                                    Req_test.c.version_date == obj.version_date)))
            objs_rs =  sel.execute() 
            test_version = ''            
            for row in objs_rs:
                num, = row                 
                if num:
                    test_version = str(obj.task_sys.abbr)+'_'+str(obj.version_date)
            return test_version
        
        def download_task_id(value, obj):
            return '<a href="/tasks/%s/%d">%s</a>' % (task_type, obj.id, value)

        fields_convert_map = {'is_mine':download_is_mine,'memo':memo,
            'test_version':download_test_version,
            'task_id':download_task_id,'test_version':test_version,'change_num':change_num,
        'test_finish_rate':test_finish_rate,'req_modified_date':req_modified_date,
        'req_finish_end_date':req_finish_end_date,'design_finish_end_date':design_finish_end_date,
        'req_close_date':req_close_date,'design_close_date':design_close_date,
        'version_date':version_date,'test_beginDate':test_beginDate,
        'test_finish_beginDate':test_finish_beginDate,'test_endDate':test_endDate,
        'test_finish_endDate':test_finish_endDate,'uat_begin_date':uat_begin_date,
        'uat_finish_begin_date':uat_finish_begin_date,'uat_end_date':uat_end_date,
        'uat_finish_end_date':uat_finish_end_date,'func_inst_begin_date':func_inst_begin_date,
        'func_inst_finish_begin_date':func_inst_finish_begin_date,'func_inst_end_date':func_inst_end_date,
        'func_inst_finish_end_date':func_inst_finish_end_date,'tune_inst_begin_date':tune_inst_begin_date,
        'tune_inst_finish_begin_date':tune_inst_finish_begin_date,'tune_inst_end_date':tune_inst_end_date,
        'tune_inst_finish_end_date':tune_inst_finish_end_date}
        return view.download('%s.xls' % task_type, action='download', timeout=0,
            fields_convert_map=fields_convert_map)
    else:
        task_type_name = get_task_type_name(task_type)
        data = {'task_type':task_type,'task_type_name':task_type_name,'query_form':query_view.form}
        
        return g_views.generic_list(model, get_url, layout=layout, add_button_text='增加%s工作任务' % task_type_name,
            template='tasks_develop_list.html', view=view, data=data, json_result=True)

@expose('/tasks/<task_type>/add')
def tasks_develop_add(task_type):
    from uliweb.utils.generic import AddView
    from uliweb.orm import get_model
    from uliweb.form.template_layout import TemplateLayout
    from forms import TaskAddForm, TaskAddDevelopForm
    from uliweb import settings
    from functools import partial
    from uliweb.form.layout import TableLayout
    
    if task_type == 'researches':
        flash('请从开发任务处添加可研任务')
        return redirect('/tasks/develop/list')
    
    get_url = g_views.get_url('/tasks/%s' % task_type, restful=True)
    model_name = get_model_name(task_type)
    Task = get_model(model_name)
    
    System = get_model('system')
    Requirement = get_model('requirement')
    
    def post_created_form(fcls, model):
        Assignment = get_model('assignment')
        
        fcls.task_sys.query = request.user.users_systems.all()
        fcls.assignment.query = Assignment.get_user_assignments(request.user, not_in=settings.get_var('PARA/ASS_NOT')).order_by(Assignment.c.ass_id)
#        fcls.requirement.choices = Requirement.get_user_requirements_choices(request.user, not_in=('19', '1A', 'FN'))
        fcls.layout_class = TemplateLayout
        if task_type == 'develop':
            fcls.task_type.choices = settings.PARA.TASK_TYPE_DEVELOP
#            fcls.requirement.choices = Requirement.get_user_requirements_choices(request.user, not_in=('19', '1A', 'FN'))
            fcls.version_headerId.choices = [('', '')]
            fcls.requirement.choices = [('', '')]
            fcls.assignment.choices = [('', '')]
            fcls.task_type.choices = [('', '')]
            fcls.layout = 'layout_tasks_add.html'
#            fcls.layout_class = TableLayout
            
        elif task_type == 'nondevelop':
            fcls.requirement.choices = Requirement.get_user_requirements_choices(request.user, not_in=settings.get_var('PARA/REQ_NOT'))
#            fcls.assignment.query = Assignment.get_user_assignments(request.user, not_in=('FN',)).order_by(Assignment.c.ass_id)
            fcls.task_type.choices = settings.PARA.TASK_TYPE_NONDEVELOP
            fcls.layout = 'layout_tasks_add_nondevelop.html'
        else:
            fcls.requirement.choices = Requirement.get_user_requirements_choices(request.user, not_in=settings.get_var('PARA/REQ_NOT'))
            fcls.layout = 'layout_tasks_add_researches.html'
#            fcls.assignment.query = Assignment.get_user_assignments(request.user, not_in=('FN',)).order_by(Assignment.c.ass_id)
            
    def pre_save(data):
        sys = System.get(data['task_sys'])
        #如果是可研任务，则task_type是缺省值，直接赋值为'05'
        if task_type == 'researches':
            data['task_type'] = '05'
        type = data['task_type']
        if sys:
            _id = sys.sys_id
        else:
            _id = 'KF%02d' % request.user._kfzx_
        v = Task.filter(Task.c.task_id.like('%s_%s_%%' % (_id, type))).order_by(Task.c.task_id.desc()).values_one('task_id')
        if not v:
            data['task_id'] = '%s_%s_%06d' % (_id, type, 1)
        else:
            v = v[0]
            _len = len('%s_%s_' % (_id, type))
            data['task_id'] = v[:_len] + '%06d' % (int(v[_len:])+1)
        #TODO 如果用户与系统不是一个开发中心，则如何处理？
#        data['kfzx'] = request.user._kfzx_
        #修改在添加时使用request.user的开发中心为使用系统的开发中心
        if sys:
            data['kfzx'] = sys._kfzx_
        else:
            if request.user._kfzx_:
                data['kfzx'] = request.user._kfzx_
        #增加tx的处理，从对应的requirement中获取
        Requirement = get_model('requirement')
        if data.get('requirement'):
            req = Requirement.get(data['requirement'])
            data['tx'] = req.tx
        #如果有父任务ID，则使用父任务信息
        if task_type == 'develop':
            if data['version_headerId']:
                parent = Task.get(int(data['version_headerId']))
                data['version_date'] = parent.version_date
                
            #处理上传test_plan文件
            if 'test_plan' in data and data['test_plan']:
                data['test_plan'].filename = os.path.join(sys.sys_id, data['task_id'] + '_' + data['test_plan'].filename)
            #新建开发任务继承准开发需求的是否自主研发考核标志
            data['selfdev_if'] = Requirement.get(Requirement.c.id == data['requirement']).selfdev_if
         
    def get_form_field(name):
        from uliweb.utils.generic import RemoteField
        
        if name == 'stakeholder':
            return RemoteField('任务责任人', name=name, url='/config/users/search', default=None)
            
    if task_type == 'develop':
        form = TaskAddDevelopForm
        def post_save(obj, data):
            #如果是子任务，则要根据父任务的Plan来创建PlanExecute
            if obj.version_headerId:
                Plan = get_model('plan')
                PlanExecute = get_model('planexecute')
            
                for plan in Plan.filter(Plan.c.task==obj._version_headerId_).filter(Plan.systems.in_(obj._task_sys_)):
                    e = PlanExecute(task=obj.id, plan=plan.id, system=obj._task_sys_, type=plan.type)
                    e.save()
        
    else:
        form = TaskAddForm
        post_save = None
    task_type_name = get_task_type_name(task_type)
    template_data = {'task_type':task_type,'task_type_name':task_type_name}
    view = AddView(Task, partial(get_url, 'view'), pre_save=pre_save, post_save=post_save,
        post_created_form=post_created_form, form_cls=form, get_form_field=get_form_field,
        template_data=template_data, success_data=True)
    
    if task_type == 'develop':
        return view.run(json_result=True)
    else:
        return view.run()
#    result = g_views.generic_add(Task, get_url=get_url, layout=layout, 
#        title='增加新%s任务' % task_type_name,  
#        template='tasks_develop_add.html', view=view, data=data)
#        
#    return result

def can_modify(obj, task_type):
    from uliweb import request
    
    flag = False
    if task_type == 'develop':
        if obj.task_sys.users.has(request.user):
            flag = True
    else:
        if obj.task_sys and obj.task_sys.users.has(request.user):
            flag = True
        else:
            if obj._kfzx_ == request.user._kfzx_ and (request.user.is_gm or obj._modified_user_ == request.user.id):
                flag = True
    return flag

def can_delete(obj, task_type):
    from uliweb import request
    
    return request.user.is_superuser or (obj._kfzx_ == request.user._kfzx_ and request.user.is_gm)
    
@expose('/tasks/<task_type>/<int:id>/edit')
def tasks_develop_edit(task_type, id):
    from uliweb.utils.generic import EditView
    from uliweb.orm import get_model
    from uliweb.form.template_layout import TemplateLayout
    from forms import TaskDevelopEditForm, TaskEditForm
    from uliweb import settings
    from sqlalchemy.sql import not_
    
    get_url = g_views.get_url('/tasks/%s' % task_type, restful=True)
    model_name = get_model_name(task_type)
    Task = get_model(model_name)
    task_type_name = get_task_type_name(task_type)
    
    obj = Task.get(int(id))
    if task_type == 'develop':
        old_version_headerId = obj._version_headerId_
    else:
        old_version_headerId = None
        
    if not can_modify(obj, task_type):
        flash('你不是当前任务的维护者，不能修改当前任务')
        return redirect(get_url('view', int(id)))
    
    def pre_save(obj, data):
        if task_type == 'develop':
            if obj.version_headerId:
                parent = obj.version_headerId
                data['version_date'] = parent.version_date
                
    def post_created_form(fcls, model, obj):
        Assignment = get_model('assignment')
        fcls.assignment.query = Assignment.filter(Assignment.systems.in_(obj._task_sys_)).filter(not_(Assignment.c.stage.in_(settings.get_var('PARA/ASS_NOT')))).order_by(Assignment.c.ass_id)
        fcls.layout_class = TemplateLayout
        if task_type == 'develop':
            fcls.task_type.choices = settings.PARA.TASK_TYPE_DEVELOP
            fcls.status.choices = settings.PARA.TASK_STATUS_INPUT
            for k, v in settings.get_var('PARA/REQ_TASK_TYPES').items():
                if obj.requirement.mode in k:
                    fcls.task_type.choices = v
            
            if obj.version_headerId:
                fcls.layout = 'layout_subtasks_edit.html'
            else:
                fcls.layout = 'layout_tasks_edit.html'
        elif task_type == 'nondevelop':
            fcls.task_type.choices = settings.PARA.TASK_TYPE_NONDEVELOP
            fcls.status.choices = settings.PARA.TASK_STATUS_INPUT
            fcls.layout = 'layout_tasks_edit_nondevelop.html'
        else:
            fcls.layout = 'layout_tasks_edit_researches.html'
        
    def get_form_field(name, obj):
        from uliweb.utils.generic import RemoteField
        
        if name == 'stakeholder':
            if obj._stakeholder_:
                alt = unicode(obj.stakeholder)
            else:
                alt = ''
            return RemoteField('任务责任人', name=name, url='/config/users/search', alt=alt, default=None)
    
    if task_type == 'develop':
        form = TaskDevelopEditForm
        TaskDevelopEditForm.obj = obj
    else:
        form = TaskEditForm
    template_data = {'task_type':task_type,'task_type_name':task_type_name,
        'title':'修改%s任务' % task_type_name}
    view = EditView(Task, ok_url=get_url('view', id), pre_save=pre_save, 
        obj=obj, post_created_form=post_created_form, form_cls=form,
        template_data=template_data, get_form_field=get_form_field)
    return view.run()
    
#    return g_views.generic_edit(Task, id, get_url, layout=layout,
#        title='修改%s任务' % task_type_name, data=data, view=view, template='tasks_develop_edit.html')

@expose('/tasks/<task_type>/<int:id>/transfer')
def tasks_develop_transfer(task_type, id):
    """
    任务迁移至其它的准开发需求下
    """
    from uliweb.utils.generic import EditView
    from uliweb.orm import get_model, do_
    
    get_url = g_views.get_url('/tasks/%s' % task_type, restful=True)
    model_name = get_model_name(task_type)
    Task = get_model(model_name)
    task_type_name = get_task_type_name(task_type)
    static_fields = ('name')
    fields = ['name', 'requirement']
    task_obj = Task.get(int(id))
    old_requirement = task_obj._requirement_
    data = {'task_type':task_type,'task_type_name':task_type_name}
    Requirement = get_model('requirement')
    Tasks_Details = get_model('tasks_details')
    
    def post_created_form(fcls, model, obj):
        fcls.requirement.choices = Requirement.get_user_requirements_choices(request.user, not_in=settings.get_var('PARA/REQ_NOT'))
    
    def pre_save(obj, data):
        req = Requirement.get(data['requirement'])
        data['tx'] = req._tx_
        
    def post_save(obj, data):
        from sqlalchemy.sql import select
        
        if old_requirement != data['requirement']:
            req = obj.requirement

            #更新当前任务的明细
            do_(Tasks_Details.table.update(Tasks_Details.c.task_id==obj.task_id).values(requirement=req.id, tx=req._tx_))
            
            ids = [obj._task_sys_]
            t_ids = []
            for task in obj.child_tasks.all():
                _id = task._task_sys_
                if _id not in ids:
                    ids.append(_id)
                    
            #将系统添加至新的准开发需求中
            req.systems.add(*ids)
                
            #将所有子任务准开发需求修改为新的准开发需求
            do_(Task.table.update(Task.c.version_headerId==obj.id).values(requirement=req.id, tx=req._tx_))
            
            #修改任务明细
            do_(Tasks_Details.table.update(Tasks_Details.c.task_id.in_(select([Task.c.task_id], Task.c.version_headerId==obj.id))).values(requirement=req.id, tx=req._tx_))
            return True
        
    def get_form_field(name, obj):
        from uliweb.utils.generic import RemoteField
        
        if name == 'requirement':
            return RemoteField('目标准开发需求', url='/requirements/search', default=None)
        
    view = EditView(Task, ok_url=get_url('view', id), obj=task_obj, template_data=data,
        fields=fields, post_created_form=post_created_form, static_fields=static_fields,
        post_save=post_save, get_form_field=get_form_field, pre_save=pre_save)
    return view.run()
    
@expose('/tasks/<task_type>/<int:id>/delete')
def tasks_develop_delete(task_type, id):
    from uliweb.orm import get_model
    from uliweb.utils.generic import DeleteView
    
    get_url = g_views.get_url('/tasks/%s' % task_type, restful=True)
    model_name = get_model_name(task_type)
    Task = get_model(model_name)
    obj = Task.get(int(id))

    if can_delete(obj, task_type):
        #检查是否还有明细记录存在
        Details = get_model('tasks_details')
        if Details.filter(Details.c.task_id==obj.task_id).count() > 0:
            flash('当前任务下还存在明细信息，请先删除')
            return redirect('/tasks/%s/%d' % (task_type, obj.id))
        if task_type == 'develop' and obj.child_tasks.all().count() > 0:
            flash('当前任务下还存在配合任务，请先删除')
            return redirect('/tasks/%s/%d' % (task_type, obj.id))
        
        #删除里程碑
        def pre_delete(obj):
            if task_type == 'develop':
                Plan = get_model('plan')
                PlanExecute = get_model('planexecute')
                PlanEdit = get_model('planedit')
                PlanExecuteDetails = get_model('planexecutedetails')
                obj.tasks_planexecutes.remove()
                obj.tasks_planedits.remove()
                obj.task_planexecutedetails.remove()
                obj.tasks_plans.remove()
            
        view = DeleteView(Task, get_url('list'), obj=obj, pre_delete=pre_delete)
        result = view.run()
        return result
    else:
        flash('你无权删除此阶段明细！')
        return redirect('/tasks/%s/%d' % (task_type, obj.id))

@expose('/tasks/<task_type>/<int:id>')
def tasks_develop_view(task_type, id):
    from uliweb.utils.generic import DetailView
    from uliweb.orm import get_model
    
    model_name = get_model_name(task_type)
    Task = get_model(model_name)
    
    obj = Task.get(int(id))
    if not obj:
        error("找不到编号为 %s 的任务" % id)

    get_url = g_views.get_url('/tasks/%s' % task_type, restful=True)

    has_plan, need_plans = False, []
    
    def get_plan(task):
        Plan = get_model('plan')
        
        if not task._version_headerId_:
            plan_objs = Plan.filter(Plan.c.task==task.id)
        else:
            condition = or_((Plan.c.task==task._version_headerId_) & Plan.systems.in_(task._task_sys_), 
                Plan.c.task==task.id)
            plan_objs = Plan.filter(condition)

        n = 0
        check = []
        for k, v in settings.get_var('PARA/PLAN_CHECK').iteritems():
            if obj.task_type in k:
                check = v
                break
        need_plans = []
        for row in plan_objs:
            n += 1
            if row.idn in check:
                check.remove(row.idn)
        if check:
            for i in check:
                for x in settings.get_var('PARA/PLAN_DEFS'):
                    if x['idn'] == i:
                        need_plans.append(x['title'])
                        break
        return n, need_plans
    def selfdev_if(value, obj):
        if obj.selfdev_if:
            selfdev_if = u'是'
        else:
            selfdev_if = u'否'
        return "<span id='selfdev_if'>%s</span>" % selfdev_if
    
    if task_type == 'develop':
        layout = 'layout_tasks_view.html'
        has_plan, need_plans = get_plan(obj)
        fields_convert_map = {'selfdev_if':selfdev_if}
    elif task_type == 'researches':
        layout = 'layout_tasks_view_researches.html'
        fields_convert_map = {}
    else:
        layout = 'layout_tasks_view_nondevelop.html'
        fields_convert_map = {}
    
    view = DetailView(Task, condition=int(id), layout=layout, fields_convert_map=fields_convert_map)
    view.types_convert_map = {orm.BooleanProperty:boolean_convert}
    
#    view.fields_convert_map = {'version_headerId':version_headerId}
    task_type_name = get_task_type_name(task_type)
    data = {'task_type':task_type,'task_type_name':task_type_name, 
        'can_modify':can_modify, 'can_delete':can_delete,
        'has_plan':has_plan, 'need_plans':need_plans}
    return g_views.generic_view(id=int(id), get_url=get_url, layout="layout_3column.html", 
        title='查看开发工作任务', template="tasks_develop_view.html", view=view, data=data)

@expose('/tasks/develop/<int:id>/newstage')
def tasks_develop_newstage(id):
    from uliweb.utils.generic import AddView
    from uliweb.orm import get_model
    from uliweb.form import SelectField, DateField
    from plugs.ui.jquery.jquery.widgets import DatePicker
    from datetime import datetime, timedelta
    from uliweb.form.template_layout import TemplateLayout

    get_url = g_views.get_url('/tasks/develop', restful=True)
    
    TaskDevelop = get_model('tasks_develop')
    obj = TaskDevelop.get(int(id))
    
    data = {}
    data['task_id'] = obj.task_id
    data['kfzx'] = obj.kfzx.name
    data['tx'] = obj.requirement.tx.name
    data['task_sys'] = obj.task_sys.name
    data['task_type'] = obj.get_display_value('task_type')
    if obj.assignment:
        data['assignment'] = obj.assignment.ass_id
    data['requirement'] = obj.requirement.req_id
    data['stage'] = obj.stage
    data['begin_time'] = obj.stage_enterTime
    data['end_time'] = datetime.now()
    data['newstage_begin_time'] = datetime.now() + timedelta(days=1)
    
    #计算下一个阶段
    choices = settings.PARA.TASK_STAGE
    index = -1
    for i, (x, y) in enumerate(choices):
        if x == obj.stage:
            index = i
            break
    if choices > -1:
        chs = choices[index+1:]
    if not chs:
        chs = choices[index:]
    newstage = SelectField('下一阶段', default=chs[0][0], choices=chs, required=True)
    newstage_begin_time = DateField('下一阶段开始时间', required=True, build=DatePicker)
    
    static_fields = ('task_id', 'requirement', 'task_sys', 'kfzx', 'task_type', 'assignment', 'tx')

    #如果是未开始状态，则进入下一阶段的界面无工作量的录入
    if obj.stage == '00':
        fields = ('task_id', 'requirement', 'task_sys', 'kfzx', 'tx', 'task_type', 'assignment',
            'stage', ('newstage', newstage), ('newstage_begin_time', newstage_begin_time), 
            'begin_time', 'end_time', 'memo')
        
    else:
        fields = ('task_id', 'requirement', 'task_sys', 'kfzx', 'tx', 'task_type', 'assignment',
            'stage', ('newstage', newstage), ('newstage_begin_time', newstage_begin_time),
            'begin_time', 'end_time', 'amount_inner_input', 'amount_outer_input', 
            'amount_inner_design', 'amount_outer_design', 'amount_inner_out8', 
            'amount_outer_out8', 'amount_inner_weekend', 'amount_outer_weekend',
            'memo')
    
    def post_created_form(fcls, model):
        fcls.layout_class = TemplateLayout
        if obj.stage == '00':
            fcls.layout = 'layout_tasks_newstage.html'
        else:
            fcls.layout = 'layout_tasks_newstage_other.html'

    def pre_save(data):
        data.update(obj.to_dict(fields=static_fields, convert=False))
        data['tx'] = obj.requirement._tx_
        data['task_id'] = obj.task_id
        data['year'] = data['begin_time'].year
        data['month'] = data['begin_time'].month
        data['year_month'] = data['year']*100 + data['month']
        
    def post_save(o, data):
        #是否完成
        if data['newstage'] == 'FN':
            Tasks_Details = get_model('tasks_details')
            d = {}
            d['task_id'] = data['task_id']
            d['kfzx'] = data['kfzx']
            d['tx'] = data['tx']
            d['task_sys'] = data['task_sys']
            d['task_type'] = data['task_type']
            d['assignment'] = data['assignment']
            d['requirement'] = data['requirement']
            d['stage'] = 'FN'
            d['begin_time'] = data['newstage_begin_time']
            d['end_time'] = data['newstage_begin_time']
            x = Tasks_Details(**d)
            x.save()
            
            #更新主记录完成状态
            obj.status = '3'
            
        #更新主记录工作量
        obj.stage_enterTime = data['newstage_begin_time']
        obj.stage = data['newstage']
        obj.amount_inner_input += data.get('amount_inner_input', 0)
        obj.amount_outer_input += data.get('amount_outer_input', 0)
        obj.amount_inner_design += data.get('amount_inner_design', 0)
        obj.amount_outer_design += data.get('amount_outer_design', 0)
        obj.amount_inner_out8 += data.get('amount_inner_out8', 0)
        obj.amount_outer_out8 += data.get('amount_outer_out8', 0)
        obj.amount_inner_weekend += data.get('amount_inner_weekend', 0)
        obj.amount_outer_weekend += data.get('amount_outer_weekend', 0)
        obj.save()
        
    from forms import TaskDevelopForm
    view = AddView('tasks_details', '/tasks/develop/%d' % int(id), fields=fields, form_cls=TaskDevelopForm,
        static_fields=static_fields, data=data, pre_save=pre_save, post_save=post_save, 
        post_created_form=post_created_form)

    data = {'task_type':'develop'}
    return g_views.generic_add(get_url=get_url, layout=layout, 
        title='进入下一阶段', view=view, template='tasks_develop_newstage.html', data=data)
 
@expose('/tasks/<task_type>/<int:id>/update')
def tasks_develop_update(task_type, id):
    """
    月末工作量补报
    """
    from uliweb.utils.generic import AddView
    from uliweb.orm import get_model
    from uliweb.form import SelectField, DateField
    from plugs.ui.jquery.jquery.widgets import DatePicker
    from datetime import timedelta, date
    from uliweb.form.template_layout import TemplateLayout
    
    get_url = g_views.get_url('/tasks/%s' % task_type, restful=True)
    model_name = get_model_name(task_type)
    Task = get_model(model_name)
    
    obj = Task.get(int(id))
    
    data = {}
    data['task_id'] = obj.task_id
    data['kfzx'] = obj.kfzx.name
    if obj.task_sys:
        data['task_sys'] = obj.task_sys.name
    if task_type in ('develop', 'researches'):
        data['tx'] = obj.requirement.tx.name
        data['requirement'] = obj.requirement.req_id
    data['task_type'] = obj.get_display_value('task_type')
    if obj.assignment:
        data['assignment'] = obj.assignment.ass_id
    else:
        data['assignment'] = ''
    if task_type == 'develop':
        data['stage'] = obj.stage
        data['begin_time'] = d = obj.stage_enterTime
        if d:
            if d.month == 12:
                data['newstage_begin_time'] = date(d.year+1, 1, 1)
            else:
                data['newstage_begin_time'] = date(d.year, d.month+1, 1)
            data['end_time'] = data['newstage_begin_time'] - timedelta(days=1)
    else:
        data['begin_time'] = obj.begin_time
        data['end_time'] = obj.end_time
        data['newstatus'] = obj.status
    
    newstage_begin_time = DateField('下个月开始时间', required=True, build=DatePicker)
    newstatus = SelectField('执行状态', default=obj.status, choices=settings.get_var('PARA/TASK_STATUS'), required=True)
    
    
    if task_type == 'develop':
        static_fields = ('task_id', 'requirement', 'task_sys', 'kfzx', 'task_type', 'assignment', 'tx')
        fields = ('task_id', 'requirement', 'task_sys', 'kfzx', 'tx', 'task_type', 'assignment',
            'stage', ('newstage_begin_time', newstage_begin_time),
            'begin_time', 'end_time', 'amount_inner_input', 'amount_outer_input', 
            'amount_inner_design', 'amount_outer_design', 'amount_inner_out8', 
            'amount_outer_out8', 'amount_inner_weekend', 'amount_outer_weekend',
            'memo')
        form_layout = 'layout_tasks_update.html'
    else:
        if task_type == 'nondevelop':
            static_fields = ('task_id', 'task_sys', 'kfzx', 'task_type', 'assignment')
        else:
            static_fields = ('task_id', 'requirement', 'task_sys', 'kfzx', 'task_type', 'assignment', 'tx')
            
        fields = ('task_id', 'requirement', 'task_sys', 'kfzx', 'tx', 'task_type', 'assignment',
            'begin_time', 'end_time', 'amount_inner_input', 'amount_outer_input', 
            'amount_inner_design', 'amount_outer_design', 'amount_inner_out8', 
            'amount_outer_out8', 'amount_inner_weekend', 'amount_outer_weekend',
            'memo', ('newstatus', newstatus))
        form_layout = 'layout_tasks_update_researches.html'
    
    def post_created_form(fcls, model):
        fcls.layout_class = TemplateLayout
        fcls.layout = form_layout
    
    def pre_save(data):
        data.update(obj.to_dict(fields=static_fields, convert=False))
        if task_type in ('develop', 'researches'):
            data['tx'] = obj.requirement._tx_
        else:
            data['tx'] = None
        data['task_id'] = obj.task_id
        data['year'] = data['begin_time'].year
        data['month'] = data['begin_time'].month
        data['year_month'] = data['year']*100 + data['month']
        
    def post_save(o, data):
        #更新主记录工作量
        if task_type == 'develop':
            #todo 考虑使用明细表获得上一阶段进入时间
            obj.stage_enterTime = data['newstage_begin_time']
        else:
            obj.status = data['newstatus']
        obj.amount_inner_input += data.get('amount_inner_input', 0)
        obj.amount_outer_input += data.get('amount_outer_input', 0)
        obj.amount_inner_design += data.get('amount_inner_design', 0)
        obj.amount_outer_design += data.get('amount_outer_design', 0)
        obj.amount_inner_out8 += data.get('amount_inner_out8', 0)
        obj.amount_outer_out8 += data.get('amount_outer_out8', 0)
        obj.amount_inner_weekend += data.get('amount_inner_weekend', 0)
        obj.amount_outer_weekend += data.get('amount_outer_weekend', 0)
        obj.save()
        
    from forms import TaskDetailsUpdateForm
    view = AddView('tasks_details', '/tasks/%s/%d' % (task_type, int(id)), fields=fields, form_cls=TaskDetailsUpdateForm,
        static_fields=static_fields, data=data, pre_save=pre_save, post_save=post_save, 
        post_created_form=post_created_form)
    
    task_type_name = get_task_type_name(task_type)
    d = {'task_type':task_type,'task_type_name':task_type_name}
    return g_views.generic_add(get_url=get_url, layout=layout, 
        title='进入下一阶段', view=view, template='tasks_develop_update.html', data=d)
    
@expose('/tasks/details/<task_type>/<id>')
def tasks_details(task_type, id):
    from uliweb.orm import get_model
    from datetime import timedelta, datetime
    
    Task = get_model(get_model_name(task_type))
    Plan = get_model('plan')
    obj = Task.get(int(id))
    Tasks_Details = get_model('tasks_details')
    objs = Tasks_Details.filter(Tasks_Details.c.task_id == obj.task_id).order_by(Tasks_Details.c.end_time)
    
    can_modified = request.user.users_systems.has(obj.task_sys)
    def check_timeout(obj):
        from uliweb import settings
        delta = timedelta(days=settings.get_var('PARA/TIMEOUT_MODIFY', 10))
        now = datetime.now()
        return now - delta <= obj.created_date <= now + delta 
            
    task_type_name = get_task_type_name(task_type)
    return {'objects':objs, 'can_modified':can_modified, 'check_timeout':check_timeout,
        'task_type':task_type,'task_type_name':task_type_name, 'plan':Plan}

@expose('/tasks/details/<id>/edit')
def tasks_details_edit(id):
    from uliweb.utils.generic import EditView
    from uliweb.orm import get_model
    from uliweb.form.template_layout import TemplateLayout
    
    Details = get_model('tasks_details')
    obj = Details.get(int(id))
    
    old_data = obj.to_dict()
    
    data = {}
#    data['task_id'] = obj.task_id
#    data['kfzx'] = obj.kfzx.name
#    data['task_sys'] = obj.task_sys.name
#    if obj.tx:
#        data['tx'] = obj.tx.name
#    data['task_type'] = obj.get_display_value('task_type')
#    if obj.assignment:
#        data['assignment'] = obj.assignment.ass_id
#    if obj.requirement:
#        data['requirement'] = obj.requirement.req_id
#    data['stage'] = obj.stage
    
    _type, Task = get_model_from_task_type(obj.task_type)
    task = Task.get(Task.c.task_id == obj.task_id)
    
    static_fields = ('task_id', 'requirement', 'task_sys', 'kfzx', 'task_type', 'assignment', 'tx')
    
    if _type == 'develop':
#        fields = ('task_id', 'requirement', 'task_sys', 'kfzx', 'tx', 'task_type', 'assignment',
#            'stage', 'begin_time', 'end_time', 'amount_inner_input', 'amount_outer_input', 
#            'amount_inner_design', 'amount_outer_design', 'amount_inner_out8', 
#            'amount_outer_out8', 'amount_inner_weekend', 'amount_outer_weekend',
#            'memo')
        fields = ('begin_time', 'end_time', 'amount_inner_input', 'amount_outer_input', 
            'amount_inner_design', 'amount_outer_design', 'amount_inner_out8', 
            'amount_outer_out8', 'amount_inner_weekend', 'amount_outer_weekend',
            'memo')
    else:
#        fields = ('task_id', 'requirement', 'task_sys', 'kfzx', 'tx', 'task_type', 'assignment',
#            'begin_time', 'end_time', 'amount_inner_input', 'amount_outer_input', 
#            'amount_inner_design', 'amount_outer_design', 'amount_inner_out8', 
#            'amount_outer_out8', 'amount_inner_weekend', 'amount_outer_weekend',
#            'memo')
        fields = ('begin_time', 'end_time', 'amount_inner_input', 'amount_outer_input', 
            'amount_inner_design', 'amount_outer_design', 'amount_inner_out8', 
            'amount_outer_out8', 'amount_inner_weekend', 'amount_outer_weekend',
            'memo')

    def post_created_form(fcls, model, obj):
        fcls.layout_class = TemplateLayout
#        if obj.stage in ('00', 'FN'):
#            fcls.layout = 'layout_tasks_details_edit_00.html'
#        else:
#            fcls.layout = 'layout_tasks_details_edit.html'
        if _type == 'develop':
            fcls.layout = 'layout_tasks_details_edit.html'
        else:
            fcls.layout = 'layout_tasks_details_edit_other.html'
    
    def pre_save(obj, data):
#        for k in static_fields:
#            del data[k]
        data['year'] = data['begin_time'].year
        data['month'] = data['begin_time'].month
        data['year_month'] = data['year']*100 + data['month']
        data['stage'] = obj.stage
        
    def post_save(o, data):
        #更新主记录工作量
#        if o.stage not in ('00', 'FN'):
        _type, Task = get_model_from_task_type(o.task_type)
        task = Task.get(Task.c.task_id == obj.task_id)
        task.amount_inner_input += data.get('amount_inner_input', 0) - old_data['amount_inner_input']
        task.amount_outer_input += data.get('amount_outer_input', 0) - old_data['amount_outer_input']
        task.amount_inner_design += data.get('amount_inner_design', 0) - old_data['amount_inner_design']
        task.amount_outer_design += data.get('amount_outer_design', 0) - old_data['amount_outer_design']
        task.amount_inner_out8 += data.get('amount_inner_out8', 0) - old_data['amount_inner_out8']
        task.amount_outer_out8 += data.get('amount_outer_out8', 0) - old_data['amount_outer_out8']
        task.amount_inner_weekend += data.get('amount_inner_weekend', 0) - old_data['amount_inner_weekend']
        task.amount_outer_weekend += data.get('amount_outer_weekend', 0) - old_data['amount_outer_weekend']
        task.save()
    
    from forms import TaskDetailsUpdateForm
    view = EditView('tasks_details', ok_url='/tasks/%s/%d#details' % (_type, task.id), obj=obj, data=data,
        form_cls=TaskDetailsUpdateForm, post_created_form=post_created_form, fields=fields, 
        static_fields=static_fields, pre_save=pre_save, post_save=post_save)
    result = view.run()
    if isinstance(result, dict):
        result.update({'task_type':_type})
    return result
    
@expose('/tasks/details/<id>/delete')
def tasks_details_delete(id):
    from uliweb.utils.generic import DeleteView
    from uliweb.orm import get_model
    
    Details = get_model('tasks_details')
    obj = Details.get(int(id))
    _type, Task = get_model_from_task_type(obj.task_type)
    task = Task.get(Task.c.task_id == obj.task_id)

    def pre_delete(obj):
        task.amount_inner_input -= obj.amount_inner_input
        task.amount_outer_input -= obj.amount_outer_input
        task.amount_inner_design -= obj.amount_inner_design
        task.amount_outer_design -= obj.amount_outer_design
        task.amount_inner_out8 -= obj.amount_inner_out8
        task.amount_outer_out8 -= obj.amount_outer_out8
        task.amount_inner_weekend -= obj.amount_inner_weekend
        task.amount_outer_weekend -= obj.amount_outer_weekend
        
        task.save()
        
#    def post_delete():
#        row = Details.filter(Details.c.task_id == task.task_id).order_by(Details.c.created_date.desc()).one()
#        if row:
#            task.stage = row.stage
#        else:
#            task.stage = '00'
#        task.save()
            
    _type, Task = get_model_from_task_type(obj.task_type)
    if request.user.is_superuser or (request.user.department in ('1', '2', '3') and request.user.is_gm):
        task = Task.get(Task.c.task_id == obj.task_id)
        view = DeleteView('tasks_details', '/tasks/%s/%d#details' % (_type, task.id), obj=obj,
            pre_delete=pre_delete)
        result = view.run()
        return result
    else:
        flash('你无权删除此阶段明细！')
        return redirect('/tasks/%s/%d#details' % (_type, obj._task_))

#@expose('/test/test2')
#def tasks_test():
#    from uliweb.utils.generic import AddView
#    from uliweb.orm import get_model
#    from uliweb.form.template_layout import TemplateLayout
#    
#    get_url = g_views.get_url('/tasks/develop')
#
#    def post_created_form(fcls, model):
#        fcls.task_type.choices = settings.PARA.TASK_TYPE_DEVELOP
#        fcls.layout_class = TemplateLayout
#        fcls.layout = 'layout_tasks_add.html'
#    
#    def pre_save(data):
#        TaskDevelop = get_model('tasks_develop')
#        System = get_model('system')
#
#        sys = System.get(data['task_sys'])
#        type = data['task_type']
#        v = TaskDevelop.filter(TaskDevelop.c.task_id.like('%04s_%s_%%' % (sys.sys_id, type))).order_by(TaskDevelop.c.task_id.desc()).values_one('task_id')
#        if not v:
#            data['task_id'] = '%04s_%s_%06d' % (sys.sys_id, type, 1)
#        else:
#            v = v[0]
#            data['task_id'] = v[:8] + '%06d' % (int(v[8:])+1)
##        data['modified_user'] = request.user.id
#
#        data['kfzx'] = sys._kfzx_
#    
#    view = AddView('tasks_develop', get_url('list'), pre_save=pre_save, 
#        post_created_form=post_created_form)
#    
#    return g_views.generic_add('tasks_develop', get_url, layout=layout, title='增加新开发任务', 
#        template='tasks_test.html', view=view)
#
@expose('/tasks/get_tasks')
def tasks_get_tasks():
    from uliweb.orm import get_model
    
    req_id = request.values.get('value')
    if not req_id:
        return json([])
    
    Requirement = get_model('requirement')
    Task = get_model('tasks_develop')
    req = Requirement.get(int(req_id))
    result = []
#    for obj in Task.filter(Task.c.requirement==int(req_id)).filter(Task.c.task_sys==req._main_sys_).filter(Task.c.version_headerId==None):
    for obj in Task.filter(Task.c.requirement==int(req_id)).filter(Task.c.version_headerId==None):
        result.append({'value':obj.id, 'text':obj.name})
    return json(result)

@expose('/tasks/get_task_parent/<task_id>')
def tasks_get_task_parent(task_id):
    from uliweb.orm import get_model
    
    Task = get_model('tasks_develop')
    task = Task.get(Task.c.id == int(task_id))
    s = []
    fields = ['test_beginDate', 'test_endDate', 'version_date', 'req_close_date',
        'design_close_date', 'uat_begin_date', 'uat_end_date', 'tune_begin_date',
        'tune_end_date', 'func_inst_begin_date', 'func_inst_end_date',
        'tune_inst_begin_date', 'tune_inst_end_date'];
    
    if task:
        s.append(task.test_level)
        for f in fields:
            s.append(task.get_display_value(f))
    return json(s)

@expose('/tasks/milestone/<int:task_id>')
def tasks_milestone(task_id):
    from uliweb.orm import get_model
    from uliweb.utils.generic import SimpleListView
    
    M = MileStone_Plan = get_model('milestone_plan')
    T = Tasks_MileStone = get_model('tasks_milestone')
    
    m = MileStone_Plan.filter(MileStone_Plan.c.task == int(task_id)).order_by(MileStone_Plan.c.plan_date)
    
    header = [
        {'name':'select', 'verbose_name':' '},
        {'name':'name', 'verbose_name':'名称'},
        {'name':'plan_date', 'verbose_name':'计划完成时间'},
#        {'name':'status', 'verbose_name':'整体状态'},
        {'name':'memo', 'verbose_name':'备注', 'width':200},
        {'name':'finish_date', 'verbose_name':'实际完成时间'},
        {'name':'finish_status', 'verbose_name':'完成状态'},
        {'name':'memo1', 'verbose_name':'备注', 'width':200},
        {'name':'actions', 'verbose_name':'动作'},
    ]
    
    def status(value, obj):
        from uliweb.utils.common import get_choice
        return get_choice(settings.get_var('PARA/MILESTONE_STATUS', []), value)
    
    def query():
        Task = get_model('tasks_develop')
        obj = Task.get(int(task_id))
        if obj.version_headerId:
            _id = obj._version_headerId_
            header = False
        else:
            _id = int(task_id)
            header = True
        for record in M.filter(M.c.task==_id).order_by(M.c.plan_date):
            r = []
            if header:
                r.append('<input type="radio" name="select" value="%d"></input>' % record.id)
            else:
                r.append('')
            r.append(record.name)
            r.append(record.plan_date)
#            r.append(record.status)
            r.append(record.memo)
            r1 = record.plan_milestones.filter(T.c.task==int(task_id)).one()
            if not r1:
                #无记录则自动添加
                r1 = T(task=obj, milestone_plan=record)
                r1.save()
                
            r.append(r1.finish_date)
            r.append(r1.status)
            r.append(r1.memo)
            if obj.task_sys.users.has(request.user):
                r.append(str(Tag('a', '修改', href='/tasks/milestone/%d/editstatus' % r1.id)))
            else:
                r.append('')
            
            yield r
      
    fields_convert_map = {'status':status, 'finish_status':status}
    view = SimpleListView(header, query, pagination=False, fields_convert_map=fields_convert_map)
    result = view.run()
    return result

@expose('/tasks/milestone/<int:m_id>/editstatus')
def tasks_milestone_editstatus(m_id):
    from uliweb.utils.generic import EditView
    from uliweb.orm import get_model
    from forms import TaskMilestoneEditForm
    
    T = get_model('tasks_milestone')
    obj = T.get(int(m_id))
    
    def pre_save(obj, data):
        d = obj.milestone_plan.plan_date
        f_d = data.get('finish_date')
        if not f_d:
            obj.status = '1'    #如果没填结束时间，则认为正常，但是要通过跑批来真正判断是否延期
        elif f_d > d:
            obj.status = '2'    #延迟
        else:
            obj.status = '3'
    
    if obj.task.task_sys.users.has(request.user):
        if not obj.milestone_plan.plan_date:
            flash('此里程碑对应的时间尚未设置，请先设置里程碑时间（如果你是配合任务，请联系主任务系统进行设置）。')
            return redirect('/tasks/develop/%d' % obj._task_)
        view = EditView('tasks_milestone', '/tasks/develop/%d#milestone' % obj._task_, 
            int(m_id), form_cls=TaskMilestoneEditForm, pre_save=pre_save)
        result = view.run()
        if isinstance(result, dict):
            result.update({'task_type':'develop'})
        return result
    else:
        flash('你无权编辑此里程碑进度！')
        return redirect('/tasks/develop/%d' % obj._task_)
    
@expose('/tasks/milestone/<int:task_id>/addplan')
def tasks_milestone_addplan(task_id):
    from uliweb.utils.generic import AddView
    from uliweb.orm import get_model
    
    Task = get_model('tasks_develop')
    T = get_model('tasks_milestone')
    obj = Task.get(int(task_id))

    def post_save(milestone, data):
        #创建Tasks_Milestone记录
        T(task=obj, milestone_plan=milestone).save()
        
        #检查所有子任务，同步所有子任务主纪录的里程碑信息
        for sub_task in obj.child_tasks.all():
            #再检查所有里程碑Tasks_Milestone，如果没有则创建
            t = T.get((T.c.task==sub_task.id) & (T.c.milestone_plan==milestone.id))
            if not t:   #不存在则创建，否则跳过
                 T(task=sub_task, milestone_plan=milestone).save()
    
    if obj.task_sys.users.has(request.user):
        view = AddView('milestone_plan', '/tasks/develop/%d#milestone' % obj.id, 
            default_data={'task':int(task_id)}, post_save=post_save)
        result = view.run()
        if isinstance(result, dict):
            result.update({'task_type':'develop'})
        return result
    else:
        flash('你无权编辑此里程碑进度！')
        return redirect('/tasks/develop/%d#milestone' % obj._task_)
    
@expose('/tasks/milestone/<int:m_id>/editplan')
def tasks_milestone_editplan(m_id):
    from uliweb.utils.generic import EditView
    from uliweb.orm import get_model
    from uliweb import settings
    
    M = get_model('milestone_plan')
    obj = M.get(int(m_id))
    
    def post_save(obj, data):
        field_name = None
        for f, msg, flag in settings.get_var('PARA/MILESTONES'):
            if obj.flag == flag:
                field_name = f
                break

        if field_name:
            setattr(obj.task, field_name, obj.plan_date)
            obj.task.save()
            for t in obj.task.child_tasks.all():
                setattr(t, field_name, obj.plan_date)
                t.save()

    if obj.task.task_sys.users.has(request.user):
        view = EditView('milestone_plan', '/tasks/develop/%d#milestone' % obj._task_, int(m_id),
            post_save=post_save)
        result = view.run()
        if isinstance(result, dict):
            result.update({'task_type':'develop'})
        return result
    else:
        flash('你无权编辑此里程碑计划！')
        return redirect('/tasks/develop/%d#milestone' % obj._task_)
    
@expose('/tasks/milestone/<int:m_id>/deleteplan')
def tasks_milestone_deleteplan(m_id):
    from uliweb.utils.generic import DeleteView
    from uliweb.orm import get_model
    
    T = get_model('tasks_milestone')
    M = get_model('milestone_plan')
    obj = M.get(int(m_id))

    def pre_delete(obj):
        T.filter(T.c.milestone_plan==obj.id).clear()
        
    if obj.task.task_sys.users.has(request.user):
        if obj.flag:
            flash('此里程碑必须存在，不能删除！')
            return redirect('/tasks/develop/%d#milestone' % obj._task_)
    
        count = T.filter((T.c.milestone_plan==obj.id) & (~(T.c.finish_date == None))).count()
        if count > 0:
            flash('当前里程碑存在已经完成的记录，请将主任务和所有子任务当前里程碑的完成时间改为空，然后再删除!')
            return redirect('/tasks/develop/%d#milestone' % obj._task_)
        view = DeleteView('milestone_plan', '/tasks/develop/%d#milestone' % obj._task_, obj=obj,
            pre_delete=pre_delete)
        result = view.run()
        return result
    else:
        flash('你无权删除此里程碑计划！')
        return redirect('/tasks/develop/%d#milestone' % obj._task_)

@expose('/tasks/milestone/<int:m_id>/checkplan')
def tasks_milestone_checkplan(m_id):
    from uliweb.orm import get_model
    
    M = get_model('milestone_plan')
    obj = M.get(int(m_id))
    if obj.task.task_sys.users.has(request.user):
        flag = True
        for r in obj.plan_milestones.all():
            flag = flag and r.status=='3'
            if not flag:
                break
        if flag:
            obj.status = '3'
            obj.save()
        else:
            if obj.status == '3':
                obj.status = '1'
                obj.save()
                
        return json({'result':'ok', 'data':obj.get_display_value('status')})
    else:
        return json({'result':'no'})

@expose('/query/workload')
def query_workload():
    from query import create_workload_query
    from uliweb.orm import get_model
    from uliweb.utils.generic import ListView
    
    Details = get_model('tasks_details')

    #处理条件
    query_view = create_workload_query(url_for(query_workload))
    c = query_view.run()
    
    condition = None
    if request.user.department == '2':
        condition = (~Details.c.task_type.in_(settings.get_var('PARA/TASK_TEST_TYPE')))
    elif request.user.department == '3':
        condition = (Details.c.task_type.in_(settings.get_var('PARA/TASK_TEST_TYPE')))
    if c.get('system'):
        condition = (Details.c.task_sys == int(c['system'])) & condition
    if c.get('begin_year_month'):
        condition = (Details.c.year_month >= int(c['begin_year_month'])) & condition
    if c.get('end_year_month'):
        condition = (Details.c.year_month <= int(c['end_year_month'])) & condition
    if c.get('task_type'):
        condition = Details.c.task_type.in_(c['task_type']) & condition
    if c.get('kfzx'):
        condition = (Details.c.kfzx == int(c['kfzx'])) & condition
    
    if condition is None:
        condition = (Details.c.id != Details.c.id)
    
    order_by = [Details.c.task_id.asc(), Details.c.begin_time.asc()]

    def task_id(value, obj):
        _type, Task = get_model_from_task_type(obj.task_type)
        record = Task.get(Task.c.task_id == value)
        if record:
            return str(Tag('a', record.task_id + '-' + record.name, href="/tasks/%s/%d" % (_type, record.id), title=record.name))
        else:
            return u"%s-(任务删除)" % obj.task_id
        
    fields_convert_map = {'task_id':task_id}
    pageno = int(request.values.get('page', 1)) - 1
    rows_per_page = int(request.values.get('rows', settings.get_var('PARA/ROWS_PER_PAGE', 10)))
    
    view =  ListView(Details, condition=condition, order_by=order_by,
        rows_per_page=rows_per_page, pageno=pageno,
        id='workload_table', fields_convert_map=fields_convert_map,
        total_fields={'total_field_name':'合计', 
            'fields':['amount_inner_input',
                'amount_inner_design',
                'amount_inner_out8',
                'amount_inner_weekend',
                'amount_outer_input',
                'amount_outer_design',
                'amount_outer_out8',
                'amount_outer_weekend']})
        
    data = {'query_form':query_view.form, 'task_type':'develop'}
    
    def download_task_id(v, obj):
        if obj.task_type == '05' and obj.year<=2011 and obj.month<=8:
            Task = get_model('researches')
        elif obj.task_type == '06' and obj.year<=2011 and obj.month<=8:
            Task = get_model('tasks')
        else:
            _type, Task = get_model_from_task_type(obj.task_type)
        record = Task.get(Task.c.task_id == obj.task_id)
        if record:
            i = "%s-%s" % (record.task_id, record.name)
        else:
            i = u"%s-(任务删除)" % obj.task_id
        return i

    if 'download' in request.GET:
        fields_convert_map = {'task_id':download_task_id}
        query = Details.filter(condition).order_by(order_by[0]).order_by(order_by[1])
        return view.download('workload.xls', action='download', timeout=0, query=query, 
            fields_convert_map=fields_convert_map)
    else:
        return g_views.generic_list(Details, url_for(query_workload), 
            template='query_workload.html', view=view, data=data, json_result=True)
    
@expose('/tasks/get_reqs')
def tasks_get_reqs():
    from uliweb.orm import get_model
    from sqlalchemy.sql import not_
    from uliweb import settings
    
    sys_id = request.values.get('value')
    if not sys_id:
        return json([])
    
    Requirement = get_model('requirement')
    reqs = Requirement.filter(Requirement.systems.in_(int(sys_id))).filter(not_(Requirement.c.stage.in_(settings.get_var('PARA/REQ_NOT')))).order_by(Requirement.c.req_id)
    s = []
    if reqs:
        s = [(x.id, unicode(x)) for x in reqs]
    return json(s)

@expose('/tasks/get_asss')
def tasks_get_asss():
    from uliweb.orm import get_model
    from sqlalchemy.sql import not_
    
    sys_id = request.values.get('value')
    if not sys_id:
        return json([])

    Assignment = get_model('assignment')
    asss = Assignment.filter(Assignment.systems.in_(int(sys_id))).filter(not_(Assignment.c.stage.in_(settings.get_var('PARA/ASS_NOT')))).order_by(Assignment.c.ass_id)
    s = []
    if asss:
        s = [(x.id, unicode(x)) for x in asss]
    return json(s)

@expose('/tasks/get_tasktypes')
def tasks_get_tasktypes():
    from uliweb.orm import get_model
    
    req_id = request.values.get('value')
    if not req_id:
        return json([])
    
    Requirement = get_model('requirement')
    Task = get_model('tasks_develop')
    req = Requirement.get(int(req_id))
    for k, v in settings.get_var('PARA/REQ_TASK_TYPES').items():
        if req.mode in k:
            return json(v)
    return json([])


@expose('/tasks/search')
def tasks_search():
    from uliweb.orm import get_model
    Tasks_develop = get_model('tasks_develop')
    Requirement = get_model('requirement')
    txt = request.values.get('term')
    if not txt:
        return json([])
    
    condition = None
    requirements_ids = [x[0] for x in Requirement.get_user_requirements(request.user).values('id')]
    #开发部门，开发主管只能看自已中心的任务，非主管看自已系统对应的任务
    if request.values.get('flag') == 1:
        if request.user.department == '2':
            if request.user.is_gm:
                condition = (Tasks_develop.c.kfzx == request.user._kfzx_) & condition
            else:
                condition = Tasks_develop.c.task_sys.in_(request.user.users_systems.ids()) & condition
    else:   
        if request.user.department == '2':
            if request.user.is_gm:
                condition = (Tasks_develop.c.kfzx == request.user._kfzx_) & condition
            else:
                condition = or_(Tasks_develop.c.requirement.in_(requirements_ids), Tasks_develop.c.task_sys.in_(request.user.users_systems.ids())) & condition
    
    if 'header' in request.values:
        condition = (Tasks_develop.c.version_headerId == None) & condition
    result = Tasks_develop.filter(and_(condition,(Tasks_develop.c.name.like('%' + txt + '%') | Tasks_develop.c.task_id.like('%' + txt + '%')))).values('id', 'task_id','name')
    search_data = []
    for x in result:
        y = {}
        y['id'] = x[0]
#        y['title'] = x[1] +'-' + x[2]
        y['title'] = x[2]
        search_data.append(y)
#    return json([{'id':x[0], 'name':(x[1]+x[2])} for x in result])
    return json(search_data)
